package com.test.io.bio.executor;

import java.util.concurrent.*;

/**
 * describe: 线程池
 *
 * @author lianying
 * @date 2020/01/21
 */
public class ExecutorPool  {
    private ThreadPoolExecutor threadPoolExecutor=null;
    /**
     * 任务队列
     */
    private LinkedBlockingQueue linkedBlockingQueue=new LinkedBlockingQueue(10);
    private ExecutorPool(){
        init();
    }
    private void init(){
        this.threadPoolExecutor=new ThreadPoolExecutor(1, 10, 120, TimeUnit.SECONDS, linkedBlockingQueue, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread=new Thread(r);
                thread.setName("bio-thread");
                return thread;
            }
        });
    }
    public static ExecutorPool getInstance() {
        return ExecutorPoolHolder.instance;
    }
    public static class ExecutorPoolHolder{
        private static ExecutorPool instance=new ExecutorPool();
    }
    /**
     * 处理任务
     *
     * @param task
     */
    public void execute(Runnable task) {
        try {
            threadPoolExecutor.execute(task);
            //通过任务拒绝异常进行使用阻塞队列的put。达到阻塞效果
        } catch (RejectedExecutionException e) {
            try {
                threadPoolExecutor.getQueue().put(task);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
